package com.nothing.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.nothing.config.StageManager;
import com.nothing.domain.UserFaceGroup;
import com.nothing.domain.UserFaceInfo;
import com.nothing.dto.FaceSearchResult;
import com.nothing.service.FaceEngineService;
import com.nothing.service.UserFaceInfoService;
import com.nothing.view.FxmlView;

import cn.hutool.core.collection.CollectionUtil;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 * 人脸图片检测
 * @author shíQíang㊚
 */

@Controller
public class FaceCheckController implements Initializable {

    @Autowired
    private FaceEngineService        faceEngineService;

    @Autowired
    private UserFaceInfoService     userFaceInfoService;

    @FXML
    private ImageView                    showImg;
    
    @FXML
    private Button                       selFile; 
    
    @FXML
    private Button                       checkUser;
    
    @FXML
    private Button                       goBack; 
    
    @FXML 
    private ChoiceBox<UserFaceGroup> groupOptions;
 
    @Lazy
    @Autowired
    private StageManager                 stageManager;

    private ObservableList<UserFaceInfo>   userList = FXCollections.observableArrayList ();
  
    @FXML
    private void exit(ActionEvent event){
        Platform.exit ();
    }
   
    @FXML
    private void goBack(ActionEvent event) throws IOException{
        stageManager.switchScene (FxmlView.FACE);
    }  

    @FXML
    void selFile(ActionEvent event){
        FileChooser fileChooser = new FileChooser ();
        fileChooser.setTitle ("选择图片");
        fileChooser.setInitialDirectory (new File (System.getProperty ("user.home")));
        fileChooser.getExtensionFilters ().addAll(
        		new FileChooser.ExtensionFilter("All Images","*.*"), 
        		new FileChooser.ExtensionFilter ("JPG","*.jpg"),
                new FileChooser.ExtensionFilter ("GIF","*.gif"), 
                new FileChooser.ExtensionFilter ("BMP","*.bmp"),
                new FileChooser.ExtensionFilter ("PNG","*.png"));
        Stage selectFile = new Stage ();
        File file = fileChooser.showOpenDialog (selectFile);
        if(file == null) return;
        showImg.setImage(new Image("file:"+file.getAbsolutePath()));
    }

    @FXML
    private void checkUser(ActionEvent event){  
        try{
            BufferedImage bufImage =  SwingFXUtils.fromFXImage(showImg.getImage(), null); 
            List<FaceSearchResult> users = faceEngineService.findUsersByFaces(bufImage,groupOptions.getSelectionModel().getSelectedItem().getId());
            if(CollectionUtil.isEmpty(users)){
                showImg.setImage(SwingFXUtils.toFXImage(bufImage,null)); 
                checkFail();
            }else{
                showImg.setImage(SwingFXUtils.toFXImage(bufImage,null)); 
                checkSuccess(users,SwingFXUtils.toFXImage(bufImage,null));
            } 
        } catch (Exception e) {
           e.printStackTrace ();
        } 
    }  
    private void checkSuccess(List<FaceSearchResult> users,Image findImg){ 
        Alert alert = new Alert (AlertType.INFORMATION);
        String tilte = "发现以下人员: ";
        String content = "";
        if(CollectionUtil.isNotEmpty(users)){
            for(FaceSearchResult user : users){
                tilte += user.getName() + " ";
                content += "姓名："+user.getName();//+" 年龄："+user.getAge() + " 性别：" + (user.getGender().equals("0") ? "女":"男") +"; \n";
            }
        } 
        alert.setTitle (tilte);
        alert.setHeaderText("验证结果");
        alert.setContentText (content);  
        ImageView iv = new ImageView ();
        iv.setImage (findImg);
        iv.setPreserveRatio(true);
        iv.setSmooth(true);
        iv.setCache(true);
        alert.setGraphic(iv); 
        alert.showAndWait();
    }

    private void checkFail(){ 
        Alert alert = new Alert(AlertType.WARNING);
        alert.setTitle("验证结果");
        alert.setHeaderText(null);
        alert.setContentText("未识别出当前人员！");
        alert.showAndWait();
    }
    
    @Override
    public void initialize(URL location,ResourceBundle resources){

        //cbRole.setItems (roles);  
        ObservableList<UserFaceGroup> options = FXCollections.observableArrayList(
                UserFaceGroup.builder().id(1L).name("特殊人").build(),
                UserFaceGroup.builder().id(2L).name("普通人").build());
        
        groupOptions.setItems(options); 
            
        setColumnProperties();
        loadUserDetails();
    }

    private void setColumnProperties(){ 
        Image  imgEdit = new Image(getClass().getResourceAsStream("/images/scan.gif"));
        showImg.setImage(imgEdit); 
    }

    private void loadUserDetails(){
        userList.clear();
        userList.addAll(userFaceInfoService.selectPage(new Page<UserFaceInfo>()).getRecords());  
    }
}
